import store from "../store"
import fileManage from './fileManage.js'
import saveFile from './saveFile.js'
import vuexSave from './vuexSave.js'
import myPromise from './myPromise.js'

let fs = fileManage.fs,userDataPath = fileManage.userDataPath;
const downloadJson = (item, index) => {
	return new Promise((resolve, reject) => {
		uni.downloadFile({
			url: item.fileUrl,
			success(res) {
				console.log('downloadFile-success', res);
				saveFile(res.tempFilePath,`${item.pageCode}.json`).then(res=>{
					if(index > -1){
						store.state.$oldPageList.splice(index,1,item);
					}else if(index === -1){
						store.state.$oldPageList.push(item);
					}
					resolve()
				},()=>{
					reject()
				})
			},
			fail(res) {
				console.log('downloadFile-fail', res);
				reject()
			}
		})
	})
}
export default newList => {
	return new Promise(resolve => {
		var promises = []
		newList.forEach(item => {
			var ifHas = store.state.$oldPageList.some((oitem,index) => {
				if (oitem.pageCode === item.pageCode) {
					if (oitem.pageConfigMd5 !== item.pageConfigMd5) {
						var promise = downloadJson(item, index)
						promises.push(promise)
					}
					return true
				}
			})
			if (!ifHas) {
				var promise = downloadJson(item, -1)
				promises.push(promise)
			}
		})
		if(promises.length > 0){
			Promise.all(myPromise(promises)).then(res=>{
				if(res.length === promises.length){
					// 每次批量下载完页面json后，将全部已下载的json信息保存到本地，便于下次比对信息判断是否需要重新下载
					fs.writeFile({
						filePath: `${userDataPath}/pageList.json`,
						data: JSON.stringify(store.state.$oldPageList),
						encoding: 'utf8',
						success(res) {
							console.log('writeFile-success', res)
						},
						fail(res) {
							console.log('writeFile-fail', res)
						}
					})
					resolve()
				}
			})
		}else{
			resolve()
		}
	})
}